package com.hsylient.javase.chapter12.demo01.udp;

import lombok.SneakyThrows;

import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SocketTwo {
    @SneakyThrows
    public static void main(String[] args) throws SocketException {
        System.out.println("=======欢迎来到聊天室===========");
        Scanner scanner = new Scanner(System.in);
        DatagramSocket datagramSocket = new DatagramSocket(10000);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0);
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, inetSocketAddress);
        while (true) {
            DatagramPacket datagramPacket1 = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 10000);
            datagramSocket.receive(datagramPacket1);
            System.out.print("黄涛：");
            System.out.println(new String(datagramPacket1.getData(), datagramPacket1.getOffset(), datagramPacket1.getLength(), StandardCharsets.UTF_8));
            System.out.print("我：");
            String message = scanner.next();
            datagramPacket.setData(message.getBytes(StandardCharsets.UTF_8));
            datagramSocket.send(datagramPacket);
        }
    }
}
